-module(fun_http_client).
-include("common.hrl").
-export([do_info/1,do_init/0,do_close/0,do_msg/1,do_time/1,async_http_request/3]).

do_init()->
	application:start(ssl),
	application:start(inets).
do_info({http, Msg}) ->
	%% 	?debug("http,Msg = ~p",[Msg]),
	async_http_response(Msg);
do_info(_) ->ok.

do_msg({reported_ply_num,PlyNum})-> 
	fun_httpc_request:send_to_background(reported_ply_num, PlyNum);

do_msg({get_cdkey_info,{Key,Hid}})-> 
	fun_httpc_request:send_to_background(get_cdkey_info, {Key}, fun_httpc_request, data_call_back, {get_cdkey_info,Hid});
do_msg(_Msg) -> ?log_error("Msg = ~p",[_Msg]).

do_close()	->ok.

do_time(_Time)->1000.

async_http_request(Method, Request, {Module, Cb_func, Cb_args}) ->
	case httpc:request(Method, Request, [], [{sync, false}, {receiver,self()}]) of
		{ok, Result} when erlang:is_reference(Result) ->
			case get(http_request_info) of
				L when erlang:is_list(L) ->
					RequestInfoList = L;
				_ ->
					RequestInfoList = []
			end,
			put(http_request_info, RequestInfoList ++ [{Result, {Module, Cb_func, Cb_args}}]),
			?log_trace("http request,method=~p,~s", [Method, request_to_string(Request)]),
			{ok, Result};
		{error, Reason} ->
			?log_warning("http request error, reason=~p", [Reason]),
			error;
		Other -> 
			?log_warning("unknown ret,value=~p", [Other]),
			error
	end.
		 
async_http_response(Response) ->
	case Response of
		{RequestId, {StatusLine, _Headers, Body}} ->
			case get(http_request_info) of
				RequestInfoList when erlang:is_list(RequestInfoList) ->
					case lists:keyfind(RequestId, 1, RequestInfoList) of
						{Key, {Module, Cb_func, Cb_args}} ->
							put(http_request_info, lists:keydelete(Key, 1, RequestInfoList)),
							try
								Module:Cb_func({StatusLine, Body}, Cb_args)
							catch E:R -> ?log_error("async_http_response callback error,E=~p,R=~p,stack=~p", [E,R,erlang:get_stacktrace()])
							end;
						_ ->
							?log_warning("invalid http request,request_id=~p", [RequestId])
					end;
				_ ->
					?log_warning("no http RequestInfoList")
			end;
		Other ->
			?log_warning("http response error,response=~p", [Other])
	end.




request_to_string(Request) ->
	case Request of
		{Url, _} ->
			io_lib:format("url=~s", [Url]);
		{Url, _, _, Data} ->
			io_lib:format("url=~s,data=~s", [Url, Data])
	end.